<#include "../../common/htmlwrap.ftl">

<@html>

    <@header title="${pageName}">

    <!--https://fengyuanchen.github.io/cropper/-->
    <!--头像裁剪-->
    <link rel="stylesheet" href="${common.staticPath}plugins/cropper/cropper.css">


    <style>
        div.browser input {
            position: absolute;
            top: 0;
            right: 0;
            margin: 0;
            border: solid transparent;
            border-width: 0 0 100px 200px;
            opacity: .0;
            filter: alpha(opacity=0);
            -o-transform: translate(250px, -50px) scale(1);
            -moz-transform: translate(-300px, 0) scale(4);
            direction: ltr;
            cursor: pointer;
        }

        div.browser label {
            background-color: #5a7bc2;
            padding: 5px 15px;
            color: white;
            font-size: 40%;
            font-weight: bold;
            cursor: pointer;
            border-radius: 2px;
            position: relative;
            overflow: hidden;
            /*display: block;*/
            width: 150px;
            margin: 20px auto 0 auto;
            box-shadow: 2px 2px 2px #888888;
        }

        div.browser span {
            cursor: pointer;
        }

    </style>

    </@header>

<body>

<!-- Content Header (Page header) -->
    <@content_header title='${pageName}'></@content_header>

<section class="content">

    <div class="row">
        <!-- form start -->
        <form role="form" action="${form_url}" id="myform" class="form-horizontal">
            <#if action=='edit'>
                <!--视频id-->
                <input name="id" value="${video.id}"
                       class="form-control" id="input_id"
                       type="hidden"
                >
            </#if>

            <div class="col-sm-12">
                <div class="box box-primary">
                <#--<div class="box-header with-border">
                    <h3 class="box-title">Quick Example</h3>
                </div>-->
                    <!-- /.box-header -->
                    <div class="box-body">

                        <div class="form-group">
                            <label for="input_name" class="col-sm-3 control-label">封面</label>
                            <div class="col-sm-9">

                                <input type="hidden" name="cover" id="input_cover" value="${video.cover}">

                                <div class="cover-browser browser">
                                    <#if video.cover??>
                                        <img src="${common.coverPath+video.cover}"
                                             class="img-responsive" id="img_cover" alt="Image"
                                             style="float: left;height: 160px;width: 160px;">
                                    <#else>
                                        <img src="${common.staticPath+"img/avatar-select.jpg"}"
                                             class="img-responsive" id="img_cover" alt="Image"
                                             style="float: left;height: 160px;width: 160px;">
                                    </#if>
                                    <label>
                                        <span>选择文件</span>
                                        <input type="file" name="cover" id="input_file_cover" class="form-control"
                                               title='选择文件'>
                                    </label>

                                    <!--<span class="btn btn-bitbucket open-avatar"><i
                                            class="fa fa-pencil-square"></i>上传图片</span>-->
                                </div>

                            </div>
                        </div>

                        <!--视频-->
                        <div class="form-group">
                            <label for="input_name" class="col-sm-3 control-label">视频</label>
                            <div class="col-sm-9">

                                <input type="hidden" name="attachmentId" id="input_video"
                                       value="${video.attachment.id!0}">

                                <div class="video-browser browser">
                                    <span class='demo-file-status'>等待上传</span>
                                    <div class="progress progress-striped active">
                                        <div class="progress-bar" role="progressbar" style="width: 0;">
                                            <span class="sr-only">0% Complete</span>
                                        </div>
                                    </div>
                                    <label>
                                        <span>选择文件</span>
                                        <input type="file" name="cover" id="input_file_video" class="form-control"
                                               title='选择文件'>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!--分区-->
                        <div class="form-group">
                            <label for="input_birthDate" class="col-sm-3 control-label">分区</label>
                            <div class="col-sm-9">
                                <#list partitions as each>
                                    <label class="radio-inline">
                                        <input type="radio" name="partitionId" value="${each.id}" required
                                            <#if (video.partition.id)?? && each.id==video.partition.id>
                                               checked
                                            </#if>
                                        >${each.name}</label>
                                </#list>
                            </div>
                        </div>

                        <!--视频标题-->
                        <div class="form-group">
                            <label for="input_title" class="col-sm-3 control-label">标题</label>
                            <div class="col-sm-9">
                                <input type="text"
                                       name="title" value="${video.title!''}"
                                       class="form-control" id="input_title"
                                       valType=""
                                       placeholder=""
                                       required>
                            </div>
                        </div>

                        <!--简介-->
                        <div class="form-group">
                            <label for="input_descript" class="col-sm-3 control-label">简介</label>
                            <div class="col-sm-9">
                                    <textarea id="input_descript"
                                              name="descript"
                                              class="form-control"
                                              style="min-height: 200px"
                                              required
                                    >${video.descript!""}</textarea>
                            </div>
                        </div>

                    </div>

                    <!-- /.box-body -->

                    <div class="box-footer">
                        <button type="button" onclick="close_iframe()" class="btn btn-default">关闭</button>
                        <button type="submit" class="btn btn-info pull-right">提交</button>
                    </div>
                </div>
            </div>
        </form>
    </div>

</section>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">封面裁剪</h4>
            </div>
            <div class="modal-body">
                <div class="row" id="avatar-container" style="padding-top: 10px">
                    <div class="col-md-8">
                        <div class="image-crop">
                            <img src=""
                                 id="image" class="img-responsive"
                                 alt="Image">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <h4>图片预览：</h4>
                        <div class="img-preview"
                             style="overflow:hidden;width:160px;height: 160px;"></div>
                        <div class="btn-group" id="cropper-btns" data-toggle="buttons">
                            <button class="btn btn-adn" id="zoomIn" type="button">放大</button>
                            <button class="btn btn-adn" id="zoomOut" type="button">缩小</button>
                            <button class="btn btn-github" id="rotateLeft" type="button">左旋转</button>
                            <button class="btn btn-github" id="rotateRight" type="button">右旋转</button>
                        <#--<button class="btn btn-warning" id="setDrag" type="button">裁剪</button>-->
                        </div>
                        <div class="clearfix"></div>
                        <div class="btn-group">
                            <div id="avatar-picker">选择封面</div>
                        <#--<input type="button" id="avatar-picker" class="form-control" value="选择头像">-->
                            <input type="button" id="cover-upload" class="form-control" value="上传">
                        </div>
                    </div>
                </div>
            </div>
        <#--<div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        &lt;#&ndash;<button type="button" class="btn btn-primary">Save changes</button>&ndash;&gt;
        </div>-->
        </div>
    </div>
</div>

    <@footer_edit>


    <script src="${common.staticPath}plugins/baiduWebupload/dist/webuploader.min.js"></script>
    <script src="${common.staticPath}plugins/cropper/cropper.js"></script>

    <!--上传插件,可以做速度计算-->
    <script src="${common.staticPath}plugins/dmuploader/dmuploader.speed.js"></script>

    <!--圆形进度条插件-->
    <script src="${common.staticPath}plugins/jquery-circle/circle-progress.js"></script>

    <!--bootstrap 弹窗-->
    <!--<script src="${common.staticPath}plugins/bootbox/bootbox.js"></script>-->

    <script type="text/javascript">

        var Progresser = (function () {

            var layer_index = null;
            var $circle = null;

            return {
                init: function () {

                    layer_index = layer.open({
                        type: 1,
                        title: false,
//                    area: '500px;',//宽度
                        closeBtn: 0,
                        shadeClose: false,
                        skin: 'yourclass',
                        content: '<div class="circle"></div>',
                        success: function (layero) {
                            $circle = layero.find('.circle');

                            $circle.circleProgress({
                                value: 0,
                                size: 100,
                                fill: {
                                    gradient: ["red", "orange"]
                                }
                            });

                        }
                    });

                    return this.layer_index;//当作id
                },
                setProgress: function (percentage) {
                    $circle.circleProgress('value', percentage / 100);
                },
                destory: function () {
                    layer.close(layer_index);
                }
            };
        })();

        var Cropper = (function () {
            //进行cropper的image标签
            var $image = $("#image");

            //放大,选装等一些按钮
            var $btns = $("#cropper-btns");//一些操作按钮
            $btns.on('click', 'button', function () {
                var $button = $(this);
                var id = $button.attr("id");
                if (id == "zoomIn") {
                    $image.cropper("zoom", 0.15);
                } else if (id == "zoomOut") {
                    $image.cropper("zoom", -0.15);
                } else if (id == "rotateLeft") {
                    $image.cropper("rotate", -90);
                } else if (id == "rotateRight") {
                    $image.cropper("rotate", 90);
                }

            });

            function getBlob(dataUrl) {
                var b64 = dataUrl.replace('data:image/jpeg;base64,', '');
                var binary = atob(b64);
                var array = [];
                for (var i = 0; i < binary.length; i++) {
                    array.push(binary.charCodeAt(i));
                }
                return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
            }

            return {
                getBlob: function () {
                    var dataUrl = $image.cropper('getCroppedCanvas', {width: 480, height: 270}).toDataURL('image/jpeg');
                    return getBlob(dataUrl);
                }
            };
        })();
    </script>

    <!--封面裁剪和上传-->
    <script type="text/javascript">
        var cover_url = "${cover_url}";
        var cover_success;

        $(function () {

            var $modal = $("#myModal");

            //进行cropper的image标签
            var $image = $("#image");

            //cropper option
            var cropperOptions = {
                aspectRatio: 4 / 4,
                preview: '.img-preview',
                crop: function (e) {

                }
            };

            //上传的图片url,base64
            var uploadedImageURL;

            //当选择了文件
            var $inputImage = $("#input_file_cover");
            $inputImage.change(function () {
                var files = this.files;
                var file;

                if (files && files.length) {
                    //第一个文件
                    file = files[0];


                    //检测mime,符合图像才继续
                    if (file.type.match('image/*')) {

                        //显示图片上传窗口
                        $modal.modal("show");

                        //清除先前存在的base64图片
                        if (uploadedImageURL) {
                            URL.revokeObjectURL(uploadedImageURL);
                        }
                        //新url
                        uploadedImageURL = URL.createObjectURL(file);

                        //模态框显示完毕之后
                        $modal.off('shown.bs.modal').on('shown.bs.modal', function (e) {
                            $image.cropper('destroy').attr('src', uploadedImageURL).cropper(cropperOptions);
                            $inputImage.val('');
                        });

                    } else {

                        layer.msg("请选择图片", {icon: 2});

                    }

                }
            });

            //上传按钮
            var $inputUpload = $("#cover-upload");
            $inputUpload.click(function () {

                //创建新表单数据
                var fd = new FormData();
                //将新文件加入表单数据,第三个参数是文件名字
                fd.append("file", Cropper.getBlob());
//                formData.append("fileFileName","photo.jpg");

                // Ajax Submit
                //http://www.w3school.com.cn/jquery/ajax_ajax.asp
                Progresser.init();
                $.ajax({
                    url: cover_url,
                    type: "POST",
                    dataType: "json",
                    data: fd,
                    cache: false,
                    contentType: false,
                    processData: false,
                    forceSync: false,
                    xhr: function () {
                        var xhrobj = $.ajaxSettings.xhr();
                        if (xhrobj.upload) {
                            xhrobj.upload.addEventListener('progress', function (event) {
                                var percent = 0;
                                var position = event.loaded || event.position;
                                var total = event.total || event.totalSize;
                                if (event.lengthComputable) {
                                    percent = Math.ceil(position / total * 100);
                                }
                                update_progress(percent);
                            }, false);
                        }

                        return xhrobj;
                    },
                    success: function (data, message, xhr) {

                        if (data.success) {
                            cover_success = true;
                            var fileMap = data.obj;
                            $("#img_cover").attr("src", fileMap.url);
                            $("#input_cover").val(fileMap.filename);
                        } else {
                            layer.msg(data.msg, {icon: 2});
                        }

                    },
                    error: function (xhr, status, errMsg) {
                        alert("上传错误！");
                    },
                    complete: function (xhr, textStatus) {

                        Progresser.destory();
                        $modal.modal("hide");
                        //一个文件提交完ajax就继续下一个文件
                        //widget.processQueue();
                    }
                });

            });

            //更新进度条
            function update_progress(percent) {
                Progresser.setProgress(percent);
                /*var percentStr = percent + '%';
                $('div.progress-bar').width(percent + "%");
                $('span.sr-only').html(percentStr + ' Complete');
                console.log("progress：" + percentStr);*/
            }

            if ($('#input_cover').val() != "") {
                cover_success = true;
            }
        });

    </script>

    <!--视频上传-->
    <script type="text/javascript">
        var video_url = "${video_url}";
        var video_success = false;

        $(function () {

            var $container = $('.video-browser');
            var $progress = $container.find(".progress");
            var $state = $container.find('span.demo-file-status');

            /***
             * 更新进度条
             */
            var lastTime;
            var lastPosition;

            function uploadProgressBar(id, percent) {

                var percentStr = percent + '%';
                $progress.find("div.progress-bar").width(percentStr);
                $progress.find("span.sr-only").html(percentStr + " Complete")

            }

            var curfile;

            $container.dmUploader({
                url: video_url,
                dataType: 'json',
                allowedTypes: 'video/mp4', /* 文件类型筛选mime-type,可验证文件类型 */
                /*extFilter: 'jpg;png;gif',文件后缀筛选,只是验证文件的后缀名*/
                fileName: "file",//服务器在后端接收文件的名字
                onInit: function () {//插件初始化完毕

                    console.log("上传插件:初始化完毕!");//调试用

                },
                onBeforeUpload: function (id) {//一个文件即将上传的时候,多个文件上传会调用多次
                    console.log("上传插件:上传即将开始");

                    lastTime = new Date().getTime();
                    lastPosition = 0;
                    $progress.slideDown();

                    //进度条初始化为0
                    uploadProgressBar(id, 0);
                }, onNewFile: function (id, file) {//当选择了文件
                    console.log("上传插件:接受文件");

                    curfile = file;

                }, onComplete: function () {//文件上传完成,多个文件的情况下是所有文件都上传完成
                    console.log("上传插件:上传完成!");

                }, onUploadProgress: function (id, percent) {//进度改变

                    uploadProgressBar(id, percent);

                }, onXhrProgress: function (event) {
                    //上传速度的制作

                    var position = event.loaded || event.position;
//                    var total = event.total || event.totalSize;
//                    console.log('position:', position, 'total:', total);

                    var middle = position - lastPosition;
                    var curTime = new Date().getTime();
                    var interval = (curTime - lastTime) / 1000; //秒

                    if (middle > 0) {
                        var size = middle / 1024; //传递的kb
                        var speed = size / interval;//kb/s
                        $state.text("上传中......" + speed.toFixed(2) + " Kb/s");
//                        console.log("size:", size, "interval:", interval, "speed:", speed);
                    }

                    lastTime = curTime;
                    lastPosition = position;

                }, onUploadSuccess: function (id, data) {//单个文件上传成功,多个文件上传时会触发多次


                    console.log("上传插件:文件id" + id + "上传完成");
                    $state.text("上传完成");
                    uploadProgressBar(id, 100);
                    //上传完成后移除进度条
                    $progress.slideUp();

                    if (data.success) {
                        video_success = true;
                        $('#input_video').val(data.obj);//实际是附件的id

                    } else {

                    }

                }, onUploadError: function (id, message) {//

                    console.log("上传插件:文件id" + id + "上传发生错误,message:" + message);
                    layer.confirm("文件id" + id + "上传发生错误,message:" + message, {icon: 3, title: '提示'}, function (index) {
                        layer.close(index);
                    });
                    $container.find("span.demo-file-status").text("错误:" + message);

                }, onFileTypeError: function (file) {
                    //文件类型错误
                    layer.alert('文件类型错误', {
                        skin: 'layui-layer-lan'
                        , closeBtn: 0
                        , shift: 4 //动画类型
                    });
                }, onFileSizeError: function (file) {
                    //文件大小错误
                    layer.alert('文件大小错误', {
                        skin: 'layui-layer-lan'
                        , closeBtn: 0
                        , shift: 4 //动画类型
                    });
                }, onFallbackMode: function (message) {
                    //浏览器不支持
                    console.log("浏览器不支持:" + message);
                    //layer.msg("浏览器不支持");
                }, onFileExtError: function (file) {
                    layer.alert('文件扩展名不对', {
                        skin: 'layui-layer-lan'
                        , closeBtn: 0
                        , shift: 4 //动画类型
                    });
                }
            });

            if ($('#input_video').val() != "") {
                $state.text("上传完成");
                $progress.slideUp();
                video_success = true;
            }

        })
    </script>

    <!--表单-->
    <script>
        $(document).ready(function () {
            //表单
            var $form = $("#myform");

            //开启验证
            $form.validatorX();

            $form.submit(function (event) {//$("button[type=submit]")
                event.preventDefault();

                //验证表单
                if (!$form.Valid()) {
                    return;
                }
                //检查视频和封面
                if (!video_success || $("#input_video").val() == "") {
                    layer.msg("请上传视频", {icon: 2});
                    return;
                }
                if (!cover_success || $("#input_cover").val() == "") {
                    layer.msg("请上传封面", {icon: 2});
                    return;
                }

                //发送ajax请求
                $.ajax({
                    url: $form.attr("action"),
                    type: "POST",
                    datatype: "json",
                    //timeout: 3000,
                    data: $form.serialize()
                }).done(function (data, textStatus) {
                    layerMsg(data.msg, data.success, function () {
                        if (data.success) {
                            close_iframe_or_refresh();
                        }
                    });
                }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log("ajax error", XMLHttpRequest, textStatus, errorThrown);
                });
            });
        });

    </script>

    </@footer_edit>
</body>

</@html>